package com.kk.miaosha.config;

import com.kk.miaosha.utils.MqConstantUtil;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author : K k
 * @date : 21:03 2020/9/26
 */
@Configuration
public class RabbitMQConfig {
    //序列化
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    //延时队列
    @Bean("delayQueue")
    public Queue delayQueue(){
        return QueueBuilder.durable(MqConstantUtil.DELAY_QUEUE)
                //如果消息过时，则会被投递到当前对应的死信交换机my-dlx-exchange
                .withArgument("x-dead-letter-exchange",MqConstantUtil.DLX_EXCHANGE)
                //如果消息过时，my-dlx-exchange会根据路由键来选择队列
                .withArgument("x-dead-letter-routing-key",MqConstantUtil.ROUTING_KEY_DELAY).build();
    }
    //死信队列
    @Bean("dlxQueue")
    public Queue dlxQueue(){
        return QueueBuilder.durable(MqConstantUtil.DLX_QUEUE).build();
    }
    //定义死信交换机
    @Bean("dlxExchange")
    public Exchange dlxExchange(){
        return ExchangeBuilder.directExchange(MqConstantUtil.DLX_EXCHANGE).build();
    }
    //绑定死信队列与交换机
    @Bean("dlxBinding")
    public Binding dlxBinding(@Qualifier("dlxExchange")Exchange exchange,@Qualifier("dlxQueue")Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with(MqConstantUtil.ROUTING_KEY_DELAY).noargs();
    }

}
